package com.jsb.laundry.controller;

import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.constant.CommonConstants;
import com.jsb.laundry.common.constant.JSBSpecialID;
import com.jsb.laundry.common.design_service.pay.properties.WechatMiniPayProperties;
import com.jsb.laundry.common.enums.ReturnStatusCode;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.http.HttpUtil;
import com.jsb.laundry.common.utils.id.IDUtil;
import com.jsb.laundry.common.utils.redis.RedisUtil;
import com.jsb.laundry.dao.ActivityDao;
import com.jsb.laundry.model.dto.CreateOrderRequest;
import com.jsb.laundry.model.dto.MonthCardBuyDto;
import com.jsb.laundry.model.dto.ProductInfoMapDto;
import com.jsb.laundry.model.entity.ActivityDetail;
import com.jsb.laundry.model.entity.ActivityModuleDetail;
import com.jsb.laundry.model.vo.PrePayVo;
import com.jsb.laundry.service.ActivityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Api(value = "洗衣活动模块", tags = "洗衣活动")
@RestController
@RequestMapping("/laundryActivity")
public class ActivityController extends BaseController{
    private static final Logger LOGGER = LoggerFactory.getLogger(ActivityController.class);

    @Resource
    private WechatMiniPayProperties wechatMiniPayProperties;
    @Resource
    private ActivityDao activityDao;
    @Resource
    private ActivityService activityService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 298、398、活动数据保存
     */
    @ApiOperation(value = "月卡数据保存", notes = "月卡数据保存", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动id", required = true, paramType = "body", dataType = "String"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "body", dataType = "String"),
    })
    @Transactional
    @PostMapping("/monthCardDataSave")
    public WebResponse monthCardDataSave(@RequestBody MonthCardBuyDto data) {

        if (JSBUtil.isEmptyString(data.getUserId()) || JSBUtil.isEmptyString(data.getActivityId()) || JSBUtil.isEmptyString(data.getServeId())) {
            return WebResponse.failOfParameter();
        }
        //支付月卡这种一种价格的商品金额
        int total = activityDao.getProductPrice(data.getActivityId(), data.getServeId());

        /**
         * TODO 订单id生成
         */
        String orderId = CommonConstants.MONTH_CARD_ORDER_PREFIX + IDUtil.getPayId();

        //构建15张卡券
        List monthCardData = buildMonthCardData(data.getActivityId(), data.getUserId(), orderId);

        // 构建月卡下单list，预下单(入库)
        int res = activityDao.monthCardDataSave(monthCardData);


        PrePayVo prePayVo = new PrePayVo().setOrderId(orderId).setUserId(data.getUserId());
        //把实际支付金额存入redis中
        ProductInfoMapDto productInfoMapDto = new ProductInfoMapDto();
        productInfoMapDto.setUserId(data.getUserId()).setOrderId(orderId)
                .setTotal(total).setProductType(OrderController.getProductType(Arrays.asList(data.getActivityId())))
                .setCallbackUrl(wechatMiniPayProperties.getLaundryCallbackUrlMonthCard());
        redisUtil.setCacheObject(CommonConstants.TIMEOUT30_WAIT_PAY_ORDER + orderId, productInfoMapDto, 30, TimeUnit.MINUTES);

        return WebResponse.successData(prePayVo);
    }



    /**
     * 校服数据保存
     */
    @ApiOperation(value = "校服数据保存", notes = "校服数据保存", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动id", required = true, paramType = "body", dataType = "String"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "body", dataType = "String"),
    })
    @Transactional
    @PostMapping("/schoolDataSave")
    public WebResponse schoolDataSave(@RequestBody CreateOrderRequest data) {

        if (JSBUtil.isEmptyString(data.getUserId()) || JSBUtil.isEmptyString(data.getActivityId()) || JSBUtil.isEmptyString(data.getServeId())) {
            return WebResponse.failOfParameter();
        }
        //支付月卡这种一种价格的商品金额
        int total = activityDao.getProductPrice(data.getActivityId(), data.getServeId());
        data.getOrderInfoList().get(0).setGoodsName("").setCateName("").setEquityExplain("").setServeMsg("");
        //向订单池中添加数据（使用一张卡）
        String res = HttpUtil.sendPost("http://127.0.0.1:10003/order/userOrder/orderDataSave", null, JSONObject.toJSONString(data));
        JSONObject jsonObject = JSONObject.parseObject(res);
        String orderId = jsonObject.getJSONObject("data").getString("orderId");
        //构建包月4张卡券
        List schoolData = schoolDeal(new ActivityModuleDetail().setOrderId(orderId).setUserId(data.getUserId()));
        int var0 = activityDao.addSchoolRecord(schoolData);

        PrePayVo prePayVo = new PrePayVo().setOrderId(orderId).setUserId(data.getUserId());
        //把实际支付金额存入redis中
        ProductInfoMapDto productInfoMapDto = new ProductInfoMapDto();
        productInfoMapDto.setUserId(data.getUserId()).setOrderId(orderId)
                .setTotal(total).setProductType(OrderController.getProductType(Arrays.asList(data.getActivityId())))
                .setCallbackUrl(wechatMiniPayProperties.getLaundryCallbackUrlSchool());;
        redisUtil.setCacheObject(CommonConstants.TIMEOUT30_WAIT_PAY_ORDER + orderId, productInfoMapDto, 30, TimeUnit.MINUTES);

        return WebResponse.successData(prePayVo);
    }

    /**
     * 校服活动订单处理(userId)
     */
    @PostMapping("/schoolActivityOrder")
    public WebResponse schoolActivityOrder(@RequestBody ActivityDetail data) {
        LOGGER.info("校服活动订单处理,{}", data.getUserId());
        if (JSBUtil.isEmptyString(data.getUserId())) {
            return WebResponse.failOfParameter();
        }
        List<ActivityDetail> resultMsg = activityDao.schoolActivityOrder(data.getUserId(), JSBSpecialID.SCHOOL_MONTH_ID);

        return WebResponse.successData(resultMsg);
    }

    /**
     * 用户校服包月卡列表
     *
     * @param data
     * @return
     */
    @PostMapping("/getSchoolCardListByUserId")
    public WebResponse userSchoolCardBag(@RequestBody ActivityDetail data) {
        LOGGER.info("用户校服包月列表,{}", data.getUserId());
        if (JSBUtil.isEmptyString(data.getUserId())) {
            return WebResponse.failOfParameter();
        }
        List<ActivityDetail> resultMsg = activityDao.userSchoolCardBag(data.getUserId());

        return WebResponse.successData(resultMsg);
    }

    /**
     * 使用校服包月卡下单（userId、holdSchoolCardId、orderId）
     *
     * @param data
     * @return
     */
    @PostMapping("/useSchoolCard")
    public WebResponse useSchoolCard(@RequestBody ActivityDetail data) {
        LOGGER.info("用户校服包月列表,{}", data.getUserId());
        if (JSBUtil.isEmptyString(data.getUserId()) || JSBUtil.isEmptyString(data.getHoldSchoolCardId())) {
            return WebResponse.failOfParameter();
        }
        //判断校服包月卡是否可用
        int ok = activityDao.checkSchoolAvailable(data.getUserId(), data.getHoldSchoolCardId());
        if (ok == 0) { //包月卡不可用
            return WebResponse.success(ReturnStatusCode.SCHOOL_UNAVAILABLE.getCode(), ReturnStatusCode.SCHOOL_UNAVAILABLE.getMsg());
        }
//        int var0 = activityService.useSchoolCard(data);
        return WebResponse.successData(ok);
    }



}
